//
//  HomePageViewController.m
//  滴滴快拍
//
//  Created by dllo on 16/5/18.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "HomePageViewController.h"
#import "Header.h"

@interface HomePageViewController ()<UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) NSMutableArray *categoryArr;
@property (nonatomic, strong) BaseCollectionView *categoryCollection;
@property (nonatomic, strong) BaseCollectionView *contentCollection;
@property (nonatomic, assign) BOOL isCategoryChange;
@property (nonatomic, assign) BOOL isXiala;
@property (nonatomic, strong) UICollectionViewFlowLayout *categoryLayout;
@property (nonatomic, strong) BaseLabel *categoryLabel;

@end

@implementation HomePageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];

    [self createView];
    [self createData];

}

- (void)createView {
    self.automaticallyAdjustsScrollViewInsets = NO;

    
    [self createCategoryCollection];
    [self createContentCollection];
    [self createBar];
    
}


#pragma mark 创建分类菜单
- (void)createCategoryCollection {
    self.categoryLayout = [[UICollectionViewFlowLayout alloc] init];
    self.categoryLayout.itemSize = CGSizeMake(SCREEN_WIDTH / 6, 44);
    self.categoryLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.categoryLayout.minimumLineSpacing = 0;
    self.categoryLayout.minimumInteritemSpacing = 0;
    self.categoryLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    // 创建collection
    self.categoryCollection = [[BaseCollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH / 6 * 5, 44) collectionViewLayout:self.categoryLayout];
    [self.navigationController.navigationBar addSubview:self.categoryCollection];
    //  设置代理
    self.categoryCollection.delegate = self;
    self.categoryCollection.dataSource = self;
    // 注册
    [self.categoryCollection registerClass:[AGLCategoryCollectionCell class] forCellWithReuseIdentifier:NSStringFromClass([AGLCategoryCollectionCell class])];
    //边界回弹
    self.categoryCollection.bounces = NO;


}

- (void)viewWillAppear:(BOOL)animated {
    self.categoryCollection.hidden = NO;
    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    self.categoryCollection.hidden = YES;
}

#pragma mark 创建内容Collection
- (void)createContentCollection {
    
    UICollectionViewFlowLayout *contentLayout = [[UICollectionViewFlowLayout alloc] init];
    contentLayout.itemSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 49);
    contentLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    contentLayout.minimumLineSpacing = 0;
    contentLayout.minimumInteritemSpacing = 0;
    contentLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    // 创建collection
    self.contentCollection = [[BaseCollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 49) collectionViewLayout:contentLayout];
    [self.view addSubview:self.contentCollection];
    //  设置代理
    self.contentCollection.delegate = self;
    self.contentCollection.dataSource = self;
    // 注册
    [self.contentCollection registerClass:[AGLContentCollectionCell class] forCellWithReuseIdentifier:NSStringFromClass([AGLContentCollectionCell class])];
    [self.contentCollection registerClass:[AGLHotCollectionCell class] forCellWithReuseIdentifier:NSStringFromClass([AGLHotCollectionCell class])];
    self.contentCollection.pagingEnabled = YES;
}

#pragma mark collectionView的协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.categoryArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    AGLCategory *category = self.categoryArr[indexPath.item];
    if (collectionView == self.categoryCollection) {
        AGLCategoryCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([AGLCategoryCollectionCell class]) forIndexPath:indexPath];
        cell.cateLabel.text = category.categoryName;
        // 选中效果
        BaseView *selectBackView = [[BaseView alloc] initWithFrame:cell.frame];
        
        BaseView *selectBottomView = [[BaseView alloc] initWithFrame:CGRectMake(0, cell.frame.size.height - 5, cell.frame.size.width, 5)];
        selectBottomView.backgroundColor = [UIColor colorWithRed:244/255.0 green:159/255.0 blue:67/255.0 alpha:1];
        
        [selectBackView addSubview:selectBottomView];
        cell.selectedBackgroundView = selectBackView;
        
        return cell;
    } else if (collectionView == self.contentCollection) {
        if (indexPath.item == 0) {// 热门
            AGLHotCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([AGLHotCollectionCell class]) forIndexPath:indexPath];
#pragma mark 视频详情block传值 2.
            // 前一个界面的获得block
            //channel cell 正常跳转
            void (^block)(NSString *,NSString *) = ^(NSString *str, NSString *videoURLStr) {
                VideoDetailViewController *vidoeDetailVC = [[VideoDetailViewController alloc] init];
                vidoeDetailVC.scid = str;
//                vidoeDetailVC.videoURL = [NSURL URLWithString:videoURLStr];
                vidoeDetailVC.videoURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://gslb.miaopai.com/stream/%@.mp4", str]];
                vidoeDetailVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:vidoeDetailVC animated:YES];
                vidoeDetailVC.hidesBottomBarWhenPushed = NO;
                
            };
            
            cell.aglHotView.block = block;
            
            // topic cell true 跳转
            void (^topicBlock)(NSString *,NSString *) = ^(NSString *stpid, NSString *topicnameEncodingStr) {

                TopicViewController *topicVC = [[TopicViewController alloc] init];
                
                topicVC.stpid = stpid;
                topicVC.topicnameEncodingStr = topicnameEncodingStr;
                
                topicVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:topicVC animated:YES];
                topicVC.hidesBottomBarWhenPushed = NO;
                
            };
            
            cell.aglHotView.topicBlock = topicBlock;

            // topic cell faulse 跳转


            
            return cell;
        } else { // 除了热门的
            AGLContentCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([AGLContentCollectionCell class]) forIndexPath:indexPath];
            cell.categoryId = category.categoryId;
            
#pragma mark 视频详情block传值 2.
            // 前一个界面的获得block

            void (^block)(NSString *, NSString *) = ^(NSString *str, NSString *videoURLStr) {
                VideoDetailViewController *vidoeDetailVC = [[VideoDetailViewController alloc] init];
                vidoeDetailVC.scid = str;
                //                vidoeDetailVC.videoURL = [NSURL URLWithString:videoURLStr];
                vidoeDetailVC.videoURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://gslb.miaopai.com/stream/%@.mp4", str]];
                vidoeDetailVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:vidoeDetailVC animated:YES];
                vidoeDetailVC.hidesBottomBarWhenPushed = NO;
                
            };
             
            cell.aglContentView.block = block;
            
            
            // topic cell true 跳转
            void (^topicBlock)(NSString *,NSString *) = ^(NSString *stpid, NSString *topicnameEncodingStr) {
                
                TopicViewController *topicVC = [[TopicViewController alloc] init];
                
                topicVC.stpid = stpid;
                topicVC.topicnameEncodingStr = topicnameEncodingStr;
                
                topicVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:topicVC animated:YES];
                topicVC.hidesBottomBarWhenPushed = NO;

                
            };
            
            cell.aglContentView.topicBlock = topicBlock;
            
            // topic cell faulse 跳转
            
            void (^topicfaulseBlock)(NSString *) = ^(NSString *stpid) {
                
                TopicViewController *topicVC = [[TopicViewController alloc] init];
                topicVC.stpid = stpid;
                topicVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:topicVC animated:YES];
                topicVC.hidesBottomBarWhenPushed = NO;
            };
            
            cell.aglContentView.topicfaulseBlock = topicfaulseBlock;
            
            return cell;
        }
        
    }
    return nil;
}

#pragma mark 点击分类category
//点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (collectionView == self.categoryCollection) {
        _isCategoryChange = NO;
        [self.categoryCollection selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionCenteredHorizontally];
        self.contentCollection.contentOffset = CGPointMake(SCREEN_WIDTH * indexPath.row, 0);
    }
}
// 上下联动 上随下动
//将显示视图
//-(void)collectionView:(UICollectionView *)collectionView willDisplaySupplementaryView:(UICollectionReusableView *)view forElementKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath{

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    if (_isCategoryChange) {
        NSInteger frontcellitem = [[[collectionView indexPathsForVisibleItems]firstObject]item];
        if (collectionView == _contentCollection) {
            [self.categoryCollection selectItemAtIndexPath:[NSIndexPath indexPathForItem:frontcellitem inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionCenteredHorizontally];
        }
    }
}
// 将消失视图
//-(void)collectionView:(UICollectionView *)collectionView didEndDisplayingSupplementaryView:(UICollectionReusableView *)view forElementOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath{

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    if (_isCategoryChange) {
        NSInteger itemitem = [[[collectionView indexPathsForVisibleItems]firstObject]item];

        if (collectionView == _contentCollection) {
            [self.categoryCollection selectItemAtIndexPath:[NSIndexPath indexPathForItem:itemitem inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionCenteredHorizontally];
        }
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    _isCategoryChange = YES;
}




#pragma mark 创建下拉菜单
- (void)createBar {
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"xiala"] style:UIBarButtonItemStylePlain target:self action:@selector(clickXiala:)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor grayColor];
    _isXiala = YES;
}

- (void)clickXiala:(UIBarButtonItem *)bar {
    
    HomePageCategoryViewController *cateVC = [[HomePageCategoryViewController alloc] init];
    
    // 动画
    CATransition *backPageAnimation = [CATransition animation];
    backPageAnimation.duration = 0.5;
    backPageAnimation.type = kCATransitionMoveIn;
    backPageAnimation.subtype = kCATransitionFromBottom;
    
    [self.navigationController.view.layer addAnimation:backPageAnimation forKey:nil];
    
    // 传数组
    cateVC.categoryArr = self.categoryArr;
    [self.navigationController pushViewController:cateVC animated:NO];
    
    
#pragma mark 点击category block传值 2.
    // 前一个界面的获得block
    
    void (^block)(NSInteger) = ^(NSInteger categoryIndex) {
        [self.categoryCollection selectItemAtIndexPath:[NSIndexPath indexPathForItem:categoryIndex inSection:0] animated:NO scrollPosition:UICollectionViewScrollPositionCenteredHorizontally];
        self.contentCollection.contentOffset = CGPointMake(SCREEN_WIDTH * categoryIndex, 0);

    };
    
    cateVC.block = block;
    
}

#pragma mark 请求数据
- (void)createData {
    
    // 请求分类
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:@"http://api.miaopai.com/m/index_cate.json?unique_id=0156a9d2-fb05-3001-83e2-e2592b043531&os=android&token=&vend=miaopai&uuid=0156a9d2-fb05-3001-83e2-e2592b043531&channel=huawei&deviceId=480c97cab176ef02&version=6.3.1" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self saveData:responseObject DataName:@"category"];
        //        NSLog(@"%@", responseObject);
        NSDictionary *dic = responseObject;
        NSArray *result = dic[@"result"];
        self.categoryArr = [AGLCategory baseModalByArr:result];
        [self.categoryCollection reloadData];
        [self.contentCollection reloadData];
        // 设置默认选中
        [self.categoryCollection selectItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] animated:NO scrollPosition:UICollectionViewScrollPositionCenteredHorizontally];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"首页分类联网失败");
        NSDictionary *dic = [self getDataWithDataName:@"category"];
        if (dic == nil) {
            NSLog(@"请连网啊亲");
        } else {
            NSArray *result = dic[@"result"];
            self.categoryArr = [AGLCategory baseModalByArr:result];
            [self.categoryCollection reloadData];
            [self.contentCollection reloadData];
            // 设置默认选中
            [self.categoryCollection selectItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] animated:NO scrollPosition:UICollectionViewScrollPositionCenteredHorizontally];

        }
        
        
    }];
    

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
